package com.syl.controller;

import com.syl.Main;
import com.syl.bean.MenuBean;
import com.syl.bean.RequestMsg;
import com.syl.dao.MenuDao;
import com.syl.util.DateUtil;
import com.syl.util.DbHelp;
import com.syl.util.HttpCommon;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by syl on 2016/6/18.
 */
public class Menu {
    private List<MenuBean> beans;
    public void init_data(){
        DbHelp db = new DbHelp();
        MenuDao dao = db.getDao(MenuDao.class);
        beans = dao.getAll();
    }

    public Menu(){
        init_data();
    }

    public Menu(String select){
        init_data();

        HttpCommon hc = new HttpCommon(Main.WAIT_TIME, Main.ENCODING);
        RequestMsg msg = hc.send_get_request(Main.URL, null);
        if(msg.live){
            String html = msg.html;
            Document doc = Jsoup.parse(html);
            Elements as = doc.select(select);
            ArrayList<MenuBean> dataList = new ArrayList<MenuBean>();
            for(Element a:as){
                MenuBean menu = new MenuBean();

                String href = a.attr("href");
                String text = a.text();
                menu.setName(text);
                menu.setUrl(href);
                menu.setParentId(getType(href,null)+"");
                menu.setCreateTime(DateUtil.get4yMdHm());
                menu.setRemark(getRemark(href));

                dataList.add(menu);
            }
            save_menu(dataList);
        }
    }

    private void save_menu(ArrayList<MenuBean> dataList) {
        DbHelp db = new DbHelp();
        MenuDao dao = db.getDao(MenuDao.class);
        for(MenuBean m:dataList){
            dao.insertData(m);
        }
        db.commit();
    }

    /**
     * @param  url  要归类的url
     * @param reg  @@ 为替代的文本
     * @return 所属类别
     */
    public int getType(String url,String reg){
        reg = reg == null ? "(.*/@@/.*)" : reg;
        for(MenuBean menu:beans){
            Pattern pattern = Pattern.compile(reg.replace("@@",menu.getRemark()));
            Matcher matcher = pattern.matcher(url);
            if(matcher.matches())return menu.getId();
        }
        return 0;
    }

    private String getRemark(String href){
        String[] split = href.split("/");
        StringBuffer sb = new StringBuffer();
        for(int i=2;i<split.length-1;i++){
            sb.append(split[i]+"/");
        }
        return sb.toString();
    }

    public List<MenuBean> getBeans() {
        return beans;
    }
}
